package com.woniuxy.oa.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.woniuxy.oa.entity.Employee;
import com.woniuxy.oa.entity.PersonnelPageBean;
import com.woniuxy.oa.entity.Personnel;
import com.woniuxy.oa.exception.EmployeeException;
import com.woniuxy.oa.exception.UsernameException;
import com.woniuxy.oa.service.DepartmentService;
import com.woniuxy.oa.service.EmployeeService;
import com.woniuxy.oa.service.JobService;
import com.woniuxy.oa.service.PersonnelService;
import com.woniuxy.oa.utils.BirthdayToAgeUtil;
import com.woniuxy.oa.utils.EmployeeUtil;
import com.woniuxy.oa.utils.WebSourceToFileUtil;
@Controller
@RequestMapping("/personnel")
public class PersonnelController {
	@Autowired
	PersonnelService personnelService;
	@Autowired
	DepartmentService departmentService;
	@Autowired
	JobService jobService;
	@Autowired
	EmployeeService employeeService;
	@Autowired
	JavaMailSenderImpl sender;
	/**进入查看pageBean的页面*/
	@RequestMapping("/showpage")
	public String getShowPage(PersonnelPageBean<Personnel> pageBean, Model model) {
		model.addAttribute("jobs",jobService.getAllJobs());
		model.addAttribute("deps",departmentService.getAllDepartments());
		model.addAttribute("pageBean", getPageBeanByMultiCondition(pageBean));
		return "system/userList";
	}
	/** 进入查看单个personnel的界面 */
	@RequestMapping("/showone/{p_id}/{domethod}")
	public String getOnePersonnel(@PathVariable("p_id") Integer p_id, @PathVariable("domethod") String domethod, Model model) {
		model.addAttribute("jobs",jobService.getAllJobs());
		model.addAttribute("deps",departmentService.getAllDepartments());
		System.out.println("-----");
		System.out.println(departmentService.getAllDepartments());
		model.addAttribute("personnel", personnelService.getPersonnelByPid(p_id));
		System.out.println(personnelService.getPersonnelByPid(p_id));
		//展示和修改使用同一个模板，show的页面在前端不可修改，modify可修改
		model.addAttribute("method", domethod);
		return "system/userInfo";
	}
	/**进入添加页面*/
	@RequestMapping("/addpage")
	public String getAddPage(Model model) {
		model.addAttribute("jobs",jobService.getAllJobs());
		model.addAttribute("deps",departmentService.getAllDepartments());
		model.addAttribute("method","add");//前端识别为add，文本框可以编辑
		return "system/addUser";
	}
	/** 添加功能的实现，返回错误映射，没有错误，前端会显示添加成功*/
	@ResponseBody
	@RequestMapping("/add")
	public Object addPersonnel(Personnel personnel,String confirmPassword, MultipartFile iconfile, HttpServletRequest request) {
		Map<String, String> errors = new HashMap<String, String>();
		try {
			if(iconfile != null && iconfile.getSize() != 0) {
				String path = WebSourceToFileUtil.toFile(iconfile,  "icon");
				personnel.getEmployee().setIcon(path);
			}
			EmployeeUtil.verifyEmployee(personnel.getEmployee(), confirmPassword);
			if(employeeService.getEmployeeByUsername(personnel.getEmployee().getUsername()) != null) {
				throw new UsernameException("用户名已存在");
			}
			//储存验证信息
			String uid = UUID.randomUUID().toString();
			sendEmailVertification(personnel.getEmployee().getEmail(), uid.substring(0,4));
			request.getSession().setAttribute("registerEmailVcode", uid.substring(0, 4));
			request.getSession().setAttribute("registerPersonnel", personnel);
		} catch (Exception e) {
			if(e instanceof EmployeeException) {
				String name = e.getClass().getSimpleName();
				//将XxxException名字替换为xxxError放入错误映射
				char[] chars = name.replace("Exception", "Error").toCharArray();
				chars[0] += 32;
				String errorName = new String(chars);
				errors.put(errorName, e.getMessage());
			}else {
				e.printStackTrace();
				errors.put("systemError", "系统错误，请与管理员联系");
			}
			return errors;
		}
		return errors;
	}
	/** 邮箱确认，加入数据库*/
	@ResponseBody
	@RequestMapping(value="/addconfirm/{vcode}",produces="application/json;charset=UTF-8")
	public Object addPersonnelIntoDatabase(@PathVariable("vcode") String vcode, HttpSession session) {
		Map<String, String> info = new HashMap<String, String>();
		if(session.getAttribute("registerEmailVcode") != null && session.getAttribute("registerEmailVcode").equals(vcode)) {
			try {
				personnelService.addPersonnel((Personnel) session.getAttribute("registerPersonnel"));
			} catch (Exception e) {
				info.put("info", "添加失败，请与管理员联系");
				return info;
			}
			info.put("info","添加成功");
		}else {
			info.put("info","验证码错误");
		}
		return info;
	}
	/** 添加功能的实现，返回错误映射，没有错误，前端会显示添加成功*/
	@ResponseBody
	@RequestMapping("/modify")
	public Object modifyPersonnel(Personnel personnel,String confirmPassword, MultipartFile iconfile) {
		Map<String, String> errors = new HashMap<String, String>();
		try {
			if(iconfile != null && iconfile.getSize()!=0) {
				String path = WebSourceToFileUtil.toFile(iconfile,  "icon");
				personnel.getEmployee().setIcon(path);
			}
			EmployeeUtil.verifyEmployee(personnel.getEmployee(), confirmPassword);
			personnelService.modifyPersonnel(personnel);
		} catch (Exception e) {
			if(e instanceof EmployeeException) {
				String name = e.getClass().getSimpleName();
				//将XxxException名字替换为xxxError放入错误映射
				char[] chars = name.replace("Exception", "Error").toCharArray();
				chars[0] += 32;
				String errorName = new String(chars);
				errors.put(errorName, e.getMessage());
			}else {
				e.printStackTrace();
				errors.put("systemError", "系统错误，请与管理员联系");
			}
			return errors;
		}
		return errors;
	}
	/**删除人事表项及其对应员工*/
	@ResponseBody
	@RequestMapping("/delete/{p_id}/{id}")
	public String removePersonnel(@PathVariable("p_id") Integer p_id, @PathVariable("id") Integer id) {
		try {
			personnelService.removePersonnelByPid(p_id, id);
		} catch (Exception e) {
			e.printStackTrace();
			return "服务器异常";
		}
		return "";
	}
	/*条件查询得到pagebean的实现*/
	public PersonnelPageBean<Personnel> getPageBeanByMultiCondition(PersonnelPageBean<Personnel> pageBean) {
		//前端第一次传回来的数据不能形成带当前页数的pageBean
		if(pageBean == null) {
			pageBean = new PersonnelPageBean<Personnel>();
		}
		if(pageBean.getCurrentPage() == null) {
			pageBean.setCurrentPage(1);
		}
		//设置每页展示数
		pageBean.setPageSize(10);
		//确定当前页的正确页码
		Integer currentPage = pageBean.getCurrentPage();
		if(currentPage < 1 ) {
			pageBean.setCurrentPage(1);
		}
		if(pageBean.getEmpCondition()== null) {
			pageBean.setEmpCondition(new Employee());
		}
		Employee emp = pageBean.getEmpCondition();
		if(emp.getBirthday() != null && !emp.getBirthday().matches("^(\\d{4})-((0?[1-9])|(1[0-2]))-((0?[1-9])|([1-2][0-9])|(3[0-1]))$")) {
			//不匹配的日期设为空;该方法不使用Date的缺陷：无法识别月份对应的日期数是否错误，只能通过前端控制
			emp.setBirthday(null);
		}
		if(!EmployeeUtil.isGender(emp.getGender())) {
			emp.setGender(null);
		}
		//根据年龄的条件得到生日范围
		String[] dates = BirthdayToAgeUtil.getDateRangeByAge(pageBean.getBeginAge(), pageBean.getEndAge());
		pageBean = personnelService.getPageBeanByMultiCondition(pageBean, dates[0], dates[1]);
		return pageBean;
	}
	/**发送邮件验证码*/
	public void sendEmailVertification(String to, String verifyCode) throws MessagingException {
		MimeMessage message = sender.createMimeMessage();
		//使用helper可以发送html、文件等
		MimeMessageHelper helper = new MimeMessageHelper(message);

		helper.setFrom("meet7lee@163.com");
		helper.setTo(to);
		//设置主题防止被接收方识别为垃圾邮件
		helper.setSubject("office验证");
		String con = "<html><head><meta charset=\"utf-8\"><title></title></head>" + 
				"<body><i>尊敬的用户：</i><br><p style=\"text-indent:2em\">本次需要输入的验证码为</p>" + 
				"<p style=\"text-indent:2em\"><b>"+verifyCode+"</b></p>"+
				"<p style=\"text-indent:2em\">本次识别码30分钟后过期</p>"+
				"</body></html>";
		helper.setText(con,true);
		
		sender.send(message);
	}
	
}
